<template>
  <div :class="['depart-container', `${prefixCls}-bg`]">
    <!-- 左侧部门树 -->
    <div class="depart-left">
      <div class="tree-header">
        <el-input
          v-model="searchKeyword"
          placeholder="输入关键字进行过滤"
          prefix-icon="Search"
          clearable
        />
        <div class="tree-actions">
          <el-button type="primary" @click="handleAddRoot">
            <template #icon>
              <i class="el-icon-plus"></i>
            </template>
            新增根部门
          </el-button>
        </div>
      </div>
      <el-tree
        ref="departTree"
        :data="departList"
        :props="{ label: 'departName' }"
        node-key="id"
        highlight-current
        default-expand-all
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ data.departName }}</span>
            <div class="node-actions">
              <el-button link type="primary" @click.stop="handleAdd(data)">新增</el-button>
              <el-button link type="primary" @click.stop="handleEdit(data)">编辑</el-button>
              <el-button link type="danger" @click.stop="handleDelete(node, data)">删除</el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 右侧部门详情 -->
    <div class="depart-right">
      <div class="form-header">
        <span class="title">{{ formData.id ? '编辑部门' : '新增部门' }}</span>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级部门">
          <el-tree-select
            v-model="formData.parentId"
            :data="departTreeData"
            :props="{ label: 'departName', value: 'id' }"
            placeholder="请选择上级部门"
          />
        </el-form-item>

        <el-form-item label="部门名称" prop="departName">
          <el-input v-model="formData.departName" placeholder="请输入部门名称" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" :max="999" />
        </el-form-item>

        <el-form-item label="负责人">
          <el-input v-model="formData.leader" placeholder="请输入负责人" />
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch v-model="formData.status" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import {
  ElButton,
  ElInput,
  ElTree,
  ElTreeSelect,
  ElForm,
  ElFormItem,
  ElInputNumber,
  ElSwitch
} from 'element-plus'

// 引入样式
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/tree/style/css'
import 'element-plus/es/components/tree-select/style/css'
import 'element-plus/es/components/form/style/css'
import 'element-plus/es/components/form-item/style/css'
import 'element-plus/es/components/input-number/style/css'
import 'element-plus/es/components/switch/style/css'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'

// 使用与 analytics 相同的前缀方式
const prefixCls = 'app'

// 部门列表数据
const departList = ref([
  {
    id: 1,
    departName: '总公司',
    sort: 1,
    status: true,
    children: [
      {
        id: 11,
        departName: '研发部',
        sort: 1,
        status: true,
        children: [
          {
            id: 111,
            departName: '前端组',
            sort: 1,
            status: true
          },
          {
            id: 112,
            departName: '后端组',
            sort: 2,
            status: true
          }
        ]
      },
      {
        id: 12,
        departName: '运营部',
        sort: 2,
        status: true
      }
    ]
  }
])

// 搜索关键字
const searchKeyword = ref('')

// 部门树选择数据
const departTreeData = computed(() => [
  {
    id: 0,
    departName: '根部门',
    children: departList.value
  }
])

// 表单相关
const formRef = ref<FormInstance>()
const formData = ref({
  id: '',
  parentId: 0,
  departName: '',
  sort: 1,
  leader: '',
  phone: '',
  email: '',
  status: true
})

// 表单校验规则
const rules = {
  departName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 新增根部门
const handleAddRoot = () => {
  formData.value = {
    id: '',
    parentId: 0,
    departName: '',
    sort: departList.value.length + 1,
    leader: '',
    phone: '',
    email: '',
    status: true
  }
}

// 新增子部门
const handleAdd = (data: any) => {
  formData.value = {
    id: '',
    parentId: data.id,
    departName: '',
    sort: (data.children?.length || 0) + 1,
    leader: '',
    phone: '',
    email: '',
    status: true
  }
}

// 编辑部门
const handleEdit = (data: any) => {
  formData.value = { ...data }
}

// 删除部门
const handleDelete = async (node: any, data: any) => {
  if (data.children?.length) {
    ElMessage.warning('该部门下还有子部门，不能删除')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
      type: 'warning'
    })
    
    const parent = node.parent
    const children = parent.data.children || parent.data
    const index = children.findIndex((d: any) => d.id === data.id)
    if (index > -1) {
      children.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 取消删除
  }
}

// 选择部门节点
const handleNodeClick = (data: any) => {
  formData.value = { ...data }
}

// 保存部门
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (formData.value.id) {
      // 编辑
      const updateNode = (list: any[]) => {
        for (const item of list) {
          if (item.id === formData.value.id) {
            Object.assign(item, formData.value)
            return true
          }
          if (item.children?.length) {
            if (updateNode(item.children)) return true
          }
        }
        return false
      }
      updateNode(departList.value)
    } else {
      // 新增
      const newDepart = {
        ...formData.value,
        id: Date.now()
      }
      
      if (formData.value.parentId === 0) {
        departList.value.push(newDepart)
      } else {
        const addNode = (list: any[]) => {
          for (const item of list) {
            if (item.id === formData.value.parentId) {
              if (!item.children) item.children = []
              item.children.push(newDepart)
              return true
            }
            if (item.children?.length) {
              if (addNode(item.children)) return true
            }
          }
          return false
        }
        addNode(departList.value)
      }
    }
    
    ElMessage.success('保存成功')
    handleReset()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.value = {
    id: '',
    parentId: 0,
    departName: '',
    sort: 1,
    leader: '',
    phone: '',
    email: '',
    status: true
  }
}
</script>

<style lang="less" scoped>
.depart-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color);
}

.depart-left {
  width: 300px;
  border-right: 1px solid var(--el-border-color-light);
  padding-right: 20px;
  
  .tree-header {
    margin-bottom: 10px;
  }
  
  .tree-actions {
    margin-top: 10px;
  }
  
  :deep(.el-tree) {
    background-color: transparent;
    
    .el-tree-node__content {
      height: 40px;
      background-color: var(--el-bg-color);
      
      &:hover {
        .node-actions {
          display: flex;
        }
      }
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  
  .node-actions {
    display: none;
    gap: 8px;
  }
}

.depart-right {
  flex: 1;
  min-width: 500px;
  
  .form-header {
    margin-bottom: 20px;
    
    .title {
      font-size: 18px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }
  
  :deep(.el-form) {
    max-width: 600px;
  }
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  background-color: var(--el-bg-color);
}

:deep(.el-form-item__label) {
  color: var(--el-text-color-primary);
}
</style> 
